package com.atguigu.gmall.boot.redis.service.impl;

import com.atguigu.gmall.boot.redis.pojo.User;
import com.atguigu.gmall.boot.redis.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 陈昆昆
 * @version 1.0
 * @date 2020/6/10 21:33
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private JedisPool jedisPool;

    @Override
    public String getvalue(String key) {
        Jedis jedis = jedisPool.getResource();
        String value ="";
        if(jedis.exists(key)){
           value = jedis.get(key);
           System.out.println("从reids缓存查询出来的"+value);
        }else{
           value = "南昌第一帅哥陈昆昆";
           jedis.set(key, value);
           System.out.println("从mysql缓存查询出来的"+value);
        }
        jedis.close();
        return value;
    }

    @Override
    public void setkeyexpire(String key,String value) {
        Jedis jedis = jedisPool.getResource();
        jedis.set(key,value);
        jedis.expire(key,9);
        jedis.close();
    }

    @Override
    public User setUser(String key) {
        Jedis jedis = jedisPool.getResource();
        key = "user:"+key;
        User user = new User();

        if(jedis.exists(key)){
            Map<String, String> map = jedis.hgetAll(key);
            user.setId(Integer.parseInt(map.get("id")));
            user.setAge(Integer.parseInt(map.get("age")));
            user.setName(map.get("name"));
            System.out.println("从reids缓存查询"+user);
        }else{
            user.setId(1);
            user.setAge(18);
            user.setName("ckk");
            Map<String,String> map = new HashMap<>();
            map.put("id",user.getId().toString());
            map.put("name",user.getName());
            map.put("age",user.getAge().toString());
            String hmset = jedis.hmset(key, map);
            System.out.println("从数据库库查询出来的"+user);
        }
        jedis.close();
        return user;
    }
}
